"""
1.加密数据 userid
2.加密算法 pip install pyjwt
3.密钥 secret_key
"""
import jwt
import time
from functools import wraps
from flask import current_app, request


# 生成token
def generate_token(data):
    # 数据加密
    # 数据时效性
    """

    :param data: 要加密的数据，类型为字典
    :return:
    """
    data.update({'exp': time.time()+current_app.config['JWT_EXPIRATION_DELTA']})
    token = jwt.encode(data, current_app.config['SECRET_KEY'], algorithm='HS256')
    return token


# 解密token
def verify_token(token):
    try:
        data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
    except Exception as e:
        return None
    return data


def login_require(view_func):
    @wraps(view_func)
    def verity_token_info(*args, **kwargs):
        # 获取用户传递的token
        token = request.headers.get('token')
        # 解析token
        if verify_token(token):
            return view_func(*args, **kwargs)
        # 返回函数
        else:
            return {'status': 401, 'msg': 'token无效'}
    return verity_token_info
